package org.sean.framework.pool;

import org.sean.framework.logging.Logger;

import java.util.Collection;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 线程池
 *
 * @author xielei
 */
public abstract class AbstractTaskExecutor implements Executor {

    private final Logger logger = Logger.newInstance(this.getClass());
    private final ExecutorService poolExecutor;
    private final ExecutorService uniqueExecutor;


    protected AbstractTaskExecutor(int threadNo, String name) {
        poolExecutor = new ThreadPoolExecutor(Math.max(4, threadNo / 4), threadNo, 60L,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000), new NamedThreadFactory(name + "-task-pool"));
        uniqueExecutor = new ThreadPoolExecutor(1, 1, 60L,
                TimeUnit.DAYS, new ArrayBlockingQueue<>(1000), new NamedThreadFactory(name + "-single"));
    }

    /**
     * 执行任务
     */
    @Override
    public void execute(Runnable task) {
        try {
            poolExecutor.execute(task);
        } catch (Exception e) {
            logger.printStackTrace(e);
        }
    }


    /**
     * 执行异步任务
     */
    @Override
    public <U> CompletableFuture<U> execute(Supplier<U> supplier) {
        return CompletableFuture.supplyAsync(supplier, poolExecutor);
    }

    /**
     * 多任务执行
     */
    @Override
    public CompletableFuture[] execute(Runnable[] tasks) {
        CompletableFuture[] result = new CompletableFuture[tasks.length];
        for (int i = 0; i < tasks.length; i++) {
            result[i] = CompletableFuture.runAsync(tasks[i], poolExecutor);
        }
        return result;
    }

    /**
     * 多任务执行
     */
    @Override
    public CompletableFuture[] execute(Collection<Runnable> tasks) {
        CompletableFuture[] result = new CompletableFuture[tasks.size()];
        int i = 0;
        for (Runnable task : tasks) {
            result[i++] = CompletableFuture.runAsync(task, poolExecutor);
        }
        return result;
    }

    /**
     * 顺序执行
     */
    @Override
    public void executeOneByOne(Runnable task) {
        try {
            uniqueExecutor.execute(task);
        } catch (Exception e) {
            logger.printStackTrace(e);
        }
    }

    @Override
    public void shutdown() {
        try {
            poolExecutor.shutdown();
        } finally {
            uniqueExecutor.shutdown();
        }
    }

    public ExecutorService getPoolExecutor() {
        return poolExecutor;
    }

    public ExecutorService getUniqueExecutor() {
        return uniqueExecutor;
    }
}
